package com.heima.search.service.impl;

import com.heima.common.constant.GlobalConstant;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.pojos.ApAssociateWords;
import com.heima.search.service.ApAssociateWordsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ResponseResult search(UserSearchDto dto) {
        if (dto==null||StringUtils.isBlank(dto.getSearchWords())||dto.getPageSize()==null)
        {
            throw new CustomException(AppHttpCodeEnum.PARAMS_NOT_NULL);
        }
        if (dto.getPageSize()<0)
        {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.setPageSize(Math.min(dto.getPageSize(), GlobalConstant.MAX_PAGE_SIZE));
        List<ApAssociateWords> apAssociateWords = mongoTemplate.find(
                Query.query(Criteria.where(GlobalConstant.ASSOCIATE_WORDS_TAG).regex(".*?\\" + dto.getSearchWords() + ".*"))
                        .limit(dto.getPageSize())
                , ApAssociateWords.class);
        return ResponseResult.okResult(apAssociateWords);
    }
}
